package cn.flying.cloud.system.dict.service.impl;

import javax.annotation.Resource;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.flying.cloud.base.common.constants.Constants;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.PageRequest;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.base.redis.service.RedisService;
import cn.flying.cloud.common.enums.StatusEnum;
import cn.flying.cloud.system.dict.entity.SysDictData;
import cn.flying.cloud.system.dict.mapper.SysDictDataMapper;
import cn.flying.cloud.system.dict.service.SysDictDataService;

/**
 * <p>
 * 枚举字段码值表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-04-02 13:05:04
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RedisService redisService;

    /**
     * 分页查询枚举字段码值表数据
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<SysDictData> getPageList(PageRequest<SysDictData> request) {
        SysDictData param = request.getParam();
        LambdaQueryWrapper<SysDictData> wrapper = getLambdaQueryWrapper(param);
        Page<SysDictData> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return new PageResponse<>(page.getTotal(), (int) page.getCurrent(), page.getRecords());
    }

    /**
     * 构建查询对象
     *
     * @param param
     * @return
     */
    private LambdaQueryWrapper<SysDictData> getLambdaQueryWrapper(SysDictData param) {
        LambdaQueryWrapper<SysDictData> wrapper = new LambdaQueryWrapper<>();
        if (param != null) {
            if (Ft.String.isNotBlank(param.getDictType())) {
                wrapper.eq(SysDictData::getDictType, param.getDictType());
            }
            if (Ft.String.isNotBlank(param.getText())) {
                wrapper.like(SysDictData::getText, "%" + param.getText() + "%");
            }
            if (Ft.String.isNotBlank(param.getStatus())) {
                wrapper.eq(SysDictData::getStatus, param.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 列表查询枚举字段码值表数据
     *
     * @param sysDictData
     * @return
     */
    @Override
    public List<SysDictData> getList(SysDictData sysDictData) {
        LambdaQueryWrapper<SysDictData> wrapper = getLambdaQueryWrapper(sysDictData);
        List<SysDictData> list = this.list(wrapper);
        return list;
    }

    /**
     * 查询枚举字段码值表详情数据
     *
     * @param sysDictData
     * @return
     */
    @Override
    public SysDictData getOneObj(SysDictData sysDictData) {
        LambdaQueryWrapper<SysDictData> wrapper = getLambdaQueryWrapper(sysDictData);
        return this.getOne(wrapper);
    }


    /**
     * 新增枚举字段码值表数据
     *
     * @param sysDictData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createObj(SysDictData sysDictData) {
        return this.save(sysDictData);
    }

    /**
     * 更新枚举字段码值表数据
     *
     * @param sysDictData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateObj(SysDictData sysDictData) {
        return this.saveOrUpdate(sysDictData);
    }

    /**
     * 删除枚举字段码值表数据
     *
     * @param sysDictData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteObj(SysDictData sysDictData) {
        return this.removeById(sysDictData.getId());
    }

    /**
     * 根据Id删除
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Serializable id) {
        return this.removeById(id);
    }

    /**
     * 根据枚举类型查询枚举字典
     *
     * @param type
     * @return
     */
    @Override
    public Map<String, String> getCodeList(String type) {
        Map<Object, Object> data = redisService.hmget(Constants.ENUM_PREFIX + type);
        // 命中缓存直接返回
        if (data != null && !data.isEmpty()) {
            return data.entrySet().stream().collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> (String) e.getValue()));
        }

        SysDictData param = new SysDictData();
        param.setDictType(type);
        param.setStatus(StatusEnum.STATUS_Y.getCode());
        List<SysDictData> list = this.getList(param);
        Map<String, String> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (SysDictData dictCode : list) {
            map.put(dictCode.getCode(), dictCode.getText());
        }
        Map<String, Object> redisMap = map.entrySet().stream().collect(Collectors.toMap(e -> String.valueOf(e.getKey()), Map.Entry::getValue));

        // 缓存字典
        redisService.hmset(Constants.ENUM_PREFIX + type, redisMap);
        return map;
    }

    /**
     * 刷新缓存
     */
    @Override
    public void refresh() {
        // 1. 模糊匹配所有符合前缀的key，使用通配符*
        Set<String> keys = redisService.redisTpl().keys(Constants.ENUM_PREFIX + "*");
        if (CollectionUtils.isNotEmpty(keys)) {
            // 2. 批量删除匹配到的所有key
            redisService.redisTpl().delete(keys);
        }

        List<SysDictData> list = this.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getStatus, StatusEnum.STATUS_Y.getCode()));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        Map<String, List<SysDictData>> map = list.stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        map.forEach((type, data) -> {
            Map<String, Object> redisMap = data.stream().collect(Collectors.toMap(SysDictData::getCode, SysDictData::getText));
            // 缓存字典
            redisService.hmset(Constants.ENUM_PREFIX + type, redisMap);
        });
    }
}
